<?php

/*
	FalconKMS Killmail handling classes
	Version: 1.2
	Author: Geoff Wilson (contact@gawilson.net)

	Kill class: This class is used to save and restore kill details from the database, it allows
	for easy manipulation of killmail data without the need to write SQL, variables can be changed
	and amended in the database, on top of this, the class allows a single kill to be stored in a sensible
	fashion, and would technically allow multiple kills to be loaded into a single PHP page much easier
	(where as the 1.x code uses lots of separate variables for kills)
	
	InvolvedParty class: This class should be used only by the Kill class, it allows the kill class to store
	multiple involved parties in a proper structured fashion, as opposed to a big multidimensional array as in
	the 1.x code base.
	
	DestroyedItem class: This class is deisnged to be used by the KillClass to store details of all the destroyed
	items during a kill.
	
	1.1
		* Added status flag, 1 = fine, 0 = problem
		* Re-wrote InvolvedPaty handling
	1.0-BETA
		* Initial version
*/


include_once "functions.php";

class Kill
{
	// Variables to store kill details
	var $killID;
	var $victim;
	var $victimID;
	var $alliance;
	var $allianceID;
        var $faction;
        var $factionID;
	var $corp;
	var $corpID;
	var $ship;
	var $shipID;
        var $shipGraphicID;
	var $shipClass;
	var $shipClassID;
	var $solarSystem;
	var $solarSystemID;
	var $solarSystemSecurity;
	var $shipValue;
	var $modValue;
	var $attackerValue;

	var $finalBlowIndex; // Loaded Kill Only
	var $timestamp;
	var $killmail;

	// Arrays to neatly store involved parties and destroyed items.
	var $involvedParties;
	var $destroyedItems;
	
	// New Status Flag
	var $status;
	
	function Kill($id = 0)
	{
		$this->killID = $id;
		$this->status = 1;
		$involvedParties = array();
		$destroyedItems = array();

		// This is not a new kill, load existing details in
		if ($id != 0) 
		{
			$result = $this->loadKill();
			if ($result == 0)
			{
				$this->status = 0;
			}
		}
	}
	
	function saveKill()
	{
		if ($this->killID == 0)
		{
		
			/*
				IMPORTANT
				Must save player data from top down - Alliance -> Corp -> Player (
				This allows propagation of new ID's correctly, i've done it this way to reduce SQL load
			*/
			
			$this->factionID = getFactionID($this->faction);
                        $this->allianceID = getAllianceID($this->alliance);
                        $this->corpID = getCorpID($this->corp, $this->allianceID);
			$this->victimID = getPlayerID($this->victim, $this->corpID);

			$this->solarSystemID = getSolarSystemID($this->solarSystem);
			$this->shipID = getShipID($this->ship);
			
			// Add ship lost to value
			$this->shipValue = getItemValue(getWeaponID($this->ship));
								
			// Make sure this isn't a dupe mail
			$sql = "SELECT * FROM `kb_kill` WHERE `playerID` = '$this->victimID' AND `shipID` = '$this->shipID' AND `systemID` = '$this->solarSystemID' AND `killTime` = '$this->timestamp'";
			
			$queryResult = mysql_query($sql);
								
			if (mysql_num_rows($queryResult) > 0) return 0;
			
			else
			{
				// Save Kill Details
				$sql = "INSERT INTO `kb_kill` (`killID`, `playerID`, `corpID`, `allianceID`, `factionID`, `shipID`, `systemID`, `KillTime`)
				VALUES (NULL, '$this->victimID', '$this->corpID', '$this->allianceID', '$this->factionID', '$this->shipID', '$this->solarSystemID', '$this->timestamp')";

				$queryResult = mysql_query($sql);
				
				// Get the new KillID
				$sql = "SELECT LAST_INSERT_ID()";
				$newKillID = mysql_result($queryResult = mysql_query($sql), 0);
				
				foreach ($this->involvedParties as $involvedParty)
				{
					$result = $involvedParty->saveInvolved($newKillID);
					if ($result == 0) return 0;
				}
				
				if (count($this->destroyedItems) > 0)
				{
					foreach ($this->destroyedItems as $destroyedItem)
					{
						$this->modValue += getItemValue($destroyedItem->itemID) * $destroyedItem->quant;
						$result = $destroyedItem->saveDestroyedItem($newKillID);
						if ($result == 0) return 0;
					}
				}
				
				$killCost = $this->modValue + $this->shipValue;
				
				// Add kill and loss points :)
				$sql = "UPDATE `kb_player` SET `lossPoints` = `lossPoints` + $killCost , `netPoints` = `netPoints` - $killCost WHERE `playerID` = '" . $this->victimID . "'";
				
				$queryResult = mysql_query($sql);
				
				$killCost = $killCost / count($this->involvedParties);

				foreach ($this->involvedParties as $involvedParty)
				{
				
					$playerID = $involvedParty->playerID;
					
					$sql = "UPDATE `kb_player` SET `killPoints` = `killPoints` + $killCost , `netPoints` = `netPoints` + $killCost WHERE `playerID` = '" . $involvedParty->playerID . "'";
					
					$queryResult = mysql_query($sql);
				}
				
			}			
			return 1;
		}
	}
	
	// Delets a kill, 1 = delete sucessful, 0 = delete failed
	function deleteKill()
	{
		if ($this->killID != 0)
		{
			// Delete kill from main kill table, limit to 1 just in case :)
			$sql = "DELETE FROM `kb_kill` WHERE `killID` = '" . $this->killID . "' LIMIT 1";
			$queryResult = mysql_query($sql);
			
			// Delete involved parties
			$sql = "DELETE FROM `kb_involved` WHERE `killID` = '" . $this->killID. "'";
			$queryResult = mysql_query($sql);
			
			// Delete destroyed Items
			$sql = "DELETE FROM `kb_destroyed` WHERE `killID` = '" . $this->killID. "'";
			$queryResult = mysql_query($sql);
			
			return 1;
		}
		else
		{
			return 0;
		}
	}
	
	// Loads an existing kill
	function loadKill()
	{
		// Get Kill Details
		$sql = "SELECT * FROM `kb_kill` WHERE `killID` = '" . $this->killID . "' LIMIT 0,1";
		$queryResult = mysql_query($sql);
		
		// Make sure supplied KillID was valid
		if (mysql_num_rows($queryResult) < 1)
		{
			logError("Kill Class > loadKill() function", "Invalid killID was specified");
			return 0;
		}
		else
		{
			// Fetch the row details from the database
			$killDetails = mysql_fetch_array($queryResult);
			
			// Assign variables from database
			$this->victimID = $killDetails["playerID"];
			$this->allianceID = $killDetails["allianceID"];
                        $this->factionID = $killDetails["factionID"];
			$this->corpID = $killDetails["corpID"];
			$this->shipID = $killDetails["shipID"];
			$this->solarSystemID = $killDetails["systemID"];
			$this->timestamp = $killDetails["killTime"];
			
			// Done the easy bit, now we need to fetch String values for all the ID's
			$this->victim = getPlayerName($this->victimID);
			$this->faction = getFactionName($this->factionID);
                        $this->alliance = getAllianceName($this->allianceID);
			$this->corp = getCorpName($this->corpID);
			$this->ship = getShipName($this->shipID);
                        $this->shipGraphicID = getShipGraphicID($this->shipID);
			$this->shipClassID = getShipClassID($this->shipID);
			$this->shipClass = getShipClassName($this->shipClassID);
			$this->solarSystem = getSolarSystemName($this->solarSystemID);
			$this->solarSystemSecurity = getSolarSystemSecurity($this->solarSystemID);
			
			// Add ship lost to value
			$this->shipValue = getItemValue(getWeaponID($this->ship));
			
			// Now we need to get invovled parties
			$sql = "SELECT * FROM `kb_involved` WHERE `killID` = '" . $this->killID . "' ORDER BY `involvedID` ASC";
			$queryResult = mysql_query($sql);
			
			while ($details = mysql_fetch_array($queryResult))
			{
				$this->involvedParties[] = new InvolvedParty($details['finalBlow'], $this->timestamp);
				
				$player = getPlayerName($details['playerID']);
				$alliance = getAllianceName($details['allianceID']);
                                $faction = getFactionName($details['factionID']);
				$corp = getCorpName($details['corpID']);
				$ship = getShipName($details['shipID']);
                                $shipGraphic = getShipGraphicID($details['shipID']);
				$weapon = getWeaponName($details['weaponID']);
				$weaponGraphic = getWeaponGraphic($details['weaponID']);

				// Set all the values
				$this->involvedParties[$this->getNumberInvolved() - 1]->player = $player;
				$this->involvedParties[$this->getNumberInvolved() - 1]->playerID = $details['playerID'];
				$this->involvedParties[$this->getNumberInvolved() - 1]->faction = $faction;
				$this->involvedParties[$this->getNumberInvolved() - 1]->factionID = $details['factionID'];
				$this->involvedParties[$this->getNumberInvolved() - 1]->alliance = $alliance;
				$this->involvedParties[$this->getNumberInvolved() - 1]->allianceID = $details['allianceID'];
                                $this->involvedParties[$this->getNumberInvolved() - 1]->corp = $corp;
				$this->involvedParties[$this->getNumberInvolved() - 1]->corpID = $details['corpID'];
				$this->involvedParties[$this->getNumberInvolved() - 1]->ship = $ship;	
				$this->involvedParties[$this->getNumberInvolved() - 1]->shipID = $details['shipID'];
                                $this->involvedParties[$this->getNumberInvolved() - 1]->shipGraphicID = $shipGraphic;
				$this->involvedParties[$this->getNumberInvolved() - 1]->weapon = $weapon;
				$this->involvedParties[$this->getNumberInvolved() - 1]->weaponID = $details['weaponID'];
				$this->involvedParties[$this->getNumberInvolved() - 1]->weaponGraphic = $weaponGraphic;
								
				if ($details['finalBlow'] == 1)
				{
					$this->finalBlowIndex = $this->getNumberInvolved() - 1;
				}
			}	
			
			// Get Destroyed Items
			$sql = "SELECT SUM( `quantity` ) AS noDestroyed, `itemID`, `location` FROM `kb_destroyed` WHERE (`killID` = " . $this->killID . ") GROUP BY `itemID`";

			$queryResult = mysql_query($sql);
			
			while ($details = mysql_fetch_array($queryResult))
			{
				$itemName = getWeaponName($details['itemID']);
				$itemGraphic = getWeaponGraphic($details['itemID']);
				
				$this->destroyedItems[] = new DestroyedItem($details['location'], $details['noDestroyed']);
				
				$this->destroyedItems[$this->getNumberItems() - 1]->itemID = $details['itemID'];
				$this->destroyedItems[$this->getNumberItems() - 1]->itemName = $itemName;
				$this->destroyedItems[$this->getNumberItems() - 1]->itemGraphic = $itemGraphic;
				
				$this->modValue += getItemValue($details['itemID']) * $details['noDestroyed'];
			}			
		}
		
		return 1;
		
	}
	
	// Adds a new involved party		
	function addInvolved($player, $alliance, $faction, $corp, $ship, $weapon, $finalBlow)
	{
		// Get ID's
                $factionID = getFactionID($faction);
		$allianceID = getAllianceID($alliance);
		$corpID = getCorpID($corp, $allianceID);
		$playerID = getPlayerID($player, $corpID);
		$shipID = getShipID($ship);
		$weaponID = getWeaponID($weapon);
		$weaponGraphic = getWeaponGraphic($weaponID);
		
		// Create a new involved party
		$this->involvedParties[] = new InvolvedParty($finalBlow, $this->timestamp);
		
		// Set all the values
		$this->involvedParties[$this->getNumberInvolved() - 1]->player = $player;
		$this->involvedParties[$this->getNumberInvolved() - 1]->playerID = $playerID;
		$this->involvedParties[$this->getNumberInvolved() - 1]->alliance = $alliance;
		$this->involvedParties[$this->getNumberInvolved() - 1]->allianceID = $allianceID;
                $this->involvedParties[$this->getNumberInvolved() - 1]->faction = $faction;
		$this->involvedParties[$this->getNumberInvolved() - 1]->factionID = $factionID;
		$this->involvedParties[$this->getNumberInvolved() - 1]->corp = $corp;
		$this->involvedParties[$this->getNumberInvolved() - 1]->corpID = $corpID;
		$this->involvedParties[$this->getNumberInvolved() - 1]->ship = $ship;	
		$this->involvedParties[$this->getNumberInvolved() - 1]->shipID = $shipID;
		$this->involvedParties[$this->getNumberInvolved() - 1]->weapon = $weapon;
		$this->involvedParties[$this->getNumberInvolved() - 1]->weaponID = $weaponID;
		$this->involvedParties[$this->getNumberInvolved() - 1]->weaponGraphic = $weaponGraphic;
			
	}
	
	// Get number of involved parties
	function getNumberInvolved()
	{
		return count($this->involvedParties);
	}
	
	// Adds a new destroyed item
	function addDestroyedItem($itemName, $itemLocation, $itemQuantity)
	{
		$itemID = getWeaponID($itemName);
		$itemGraphic = getWeaponGraphic($itemID);

		$this->destroyedItems[] = new DestroyedItem($itemLocation, $itemQuantity);
		
		$this->destroyedItems[$this->getNumberItems() - 1]->itemID = $itemID;
		$this->destroyedItems[$this->getNumberItems() - 1]->itemName = $itemName;
		$this->destroyedItems[$this->getNumberItems() - 1]->itemGraphic = $itemGraphic;
	}
	
	// Returns number of destroyed items
	function getNumberItems()
	{
		return count($this->destroyedItems);
	}
	
	function dumpDetails()
	{
		print_r($this);
	}
	
}

class InvolvedParty
{
	var $player;
	var $playerID;
        var $faction;
        var $factionID;
	var $alliance;
	var $allianceID;
	var $corp;
	var $corpID;
	var $ship;
	var $shipID;
        var $shipGraphicID;
	var $weapon;
	var $weaponID;
	var $weaponGraphic;
	var $timestamp;
	var $finalBlow;
	
	// New Constructor, Lets be more sensible about how we use the database
	function InvolvedParty($finalBlow, $timestamp)
	{
		$this->finalBlow = $finalBlow;
		$this->timestamp = $timestamp;
	}
	
	function saveInvolved($killID)
	{
		// We Need to check validity of involved party now
	
		// Saves to kb_involved using supplied $killID)
		$sql = "INSERT INTO `kb_involved` (`involvedID`, `killID`, `playerID`, `corpID`, `allianceID`, `factionID`, `shipID`, `weaponID`, `finalBlow`, `involvedTime`)
		VALUES (NULL, '$killID', '$this->playerID', '$this->corpID', '$this->allianceID', '$this->factionID', '$this->shipID', '$this->weaponID', '$this->finalBlow', '$this->timestamp')";
		$queryResult = mysql_query($sql);	
	
		return 1;
	}
	
}

class DestroyedItem
{
	/*
		Locations:
		1: Equipped
		2: Cargo Bay
		3: Drone Bay
	*/
	
	var $itemName;
	var $itemID;
	var $itemGraphic;
	var $location;
	var $quant;
	
	function DestroyedItem($location, $quantity)
	{
		$this->location = $location;
		$this->quant = $quantity;
	}
	
	function saveDestroyedItem($killID)
	{
		// Validate Item
		if ($this->itemName == NULL) return 0;
		if ($this->itemID == NULL) return 0;
		
		// Save Destroyed Item to Database
		$sql = "INSERT INTO `kb_destroyed` (`destroyedID`, `killID`, `itemID`, `location`, `quantity`) 
		VALUES (NULL, '$killID', '$this->itemID', '$this->location', '$this->quant')";
		$queryResult = mysql_query($sql);
		
		return 1;		
	}
}
